package cn.syncrond.tcm.web.rmi;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import cn.syncrond.tcm.AppContext;

public class RmiClient {
	
	/**
	 * 注册地址
	 */
	private String url = "service:jmx:rmi:///jndi/rmi://localhost:1009/jmxrmi";
	
	/**
	 * jmx连接器
	 */
	private JMXConnector connector;
	
	/**
	 * MBean服务连接
	 */
	private MBeanServerConnection connection;
	
	public RmiClient(){
		// 获取配置信息中的服务地址
		String serviceUrl = AppContext.getInstance().getInitRmiServiceUrl();
		if(StringUtils.isNoneBlank(serviceUrl)){
			url = serviceUrl;
		}
	}
	
	public void connect(){
		Map<String, Object> prop = new HashMap<String, Object>();
//		prop.put(JMXConnector.CREDENTIALS, "u1");
		try {
			JMXServiceURL serviceURL = new JMXServiceURL(url);
			connector = JMXConnectorFactory.connect(serviceURL, prop);
			connection = connector.getMBeanServerConnection();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取MBean
	 * @param name
	 * @param clazz
	 * @return
	 */
	public <T> T getMBeanProxy(String name, Class<T> clazz){
		try {
			T t = JMX.newMBeanProxy(connection, new ObjectName(name), clazz);
			return t;
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 关闭连接器
	 */
	public void close(){
		IOUtils.closeQuietly(connector);
	}
}
